package com.tgjs.sphoto.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;
import com.tgjs.sphoto.activity.MainActivity;
import com.tgjs.sphoto.constant.ConstantValues;

import java.io.File;

/**
 * Created by dql on 2018/8/20.
 */

public class DownloadUtil {

	// 保存图片到手机
	@SuppressLint("StaticFieldLeak")
	public static void download(final String url ,final Context context) {

		new AsyncTask<Void, Integer, File>() {
			@Override
			protected void onPreExecute() {
				Toast.makeText(context,"Now Downloading",Toast.LENGTH_SHORT).show();
				super.onPreExecute();
			}

			@Override
			protected File doInBackground(Void... params) {
				File file = null;
				try {
					FutureTarget<File> future =
						Glide
							.with(context)
							.load(url)
							.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
					file = future.get();
					// 首先保存图片
					File pictureFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
					File appDir = new File(pictureFolder ,"SPhoto");
					if (!appDir.exists()) {
						appDir.mkdirs();
					}
					String fileName = System.currentTimeMillis() + ".jpg";
					SPUtils.getInstance().put(ConstantValues.FILENAME,fileName);
					File destFile = new File(appDir, fileName);
					FileUtils.copy(file, destFile);
					// 最后通知图库更新
					context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
							Uri.fromFile(new File(destFile.getPath()))));
				} catch (Exception e) {
					Log.e("E", e.getMessage());
				}
				return file;
			}

			@Override
			protected void onPostExecute(File file) {
				Toast.makeText(context, "Saved in Pictures/SPhoto", Toast.LENGTH_SHORT).show();
			}

			@Override
			protected void onProgressUpdate(Integer... values) {
				super.onProgressUpdate(values);
			}
		}.execute();
	}
}
